import React, {useState} from "react";
import { addTodo, incrementCounter } from "../redux/actions";
import { useSelector, useDispatch } from 'react-redux'

export default function AddTodo(props) {
 
  const dispatch = useDispatch()

  const [item, setItem] = useState("u")

  const counter = useSelector(state => state.todos.counter)

  const handleAddTodo = () => {

    if (counter) {
      console.log("ok " + counter);

      dispatch(incrementCounter(counter+1))

    } else {
      console.log("bad " + counter);

      dispatch(incrementCounter(1))
    }
    
    dispatch(addTodo(item))

    setItem("")
  };

  return (

    <div>
      <div>
        { JSON.stringify(counter)} 条
      </div>

      <input
        className="w-64 h-10 rounded"
        onChange={event => setItem(event.target.value)}
        value={item}
      />
      <button className="mx-4 w-32 h-10 bg-gray-100 border-2 boder-indigo-100 rounded-xl" onClick={handleAddTodo}>
        Add Todo
      </button>
    </div>

  )

}
